package com.songlanyun.modules.personaldata.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.DateUtils;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.exception.ConfigException;
import com.songlanyun.modules.personaldata.dao.PersonalDataDao;
import com.songlanyun.modules.personaldata.entity.PersonalDataEntity;
import com.songlanyun.modules.personaldata.service.PersonalDataService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("personalDataService")
public class PersonalDataServiceImpl extends ServiceImpl<PersonalDataDao, PersonalDataEntity> implements PersonalDataService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = MapUtil.getStr(params, "name");
        String mobile = MapUtil.getStr(params, "mobile");

        IPage<PersonalDataEntity> page = this.page(
                new Query<PersonalDataEntity>().getPage(params),
                new LambdaQueryWrapper<PersonalDataEntity>()
                        .like(StringUtils.isNotBlank(name), PersonalDataEntity::getName, name)
                        .like(StringUtils.isNotBlank(mobile), PersonalDataEntity::getMobile, mobile)
                        .orderByDesc(PersonalDataEntity::getCreateTime)
        );

        return new PageUtils(page);
    }

    @Override
    public void dispose(PersonalDataEntity personalData) {
        PersonalDataEntity data = this.baseMapper.selectById(personalData.getId());
        if (data == null) {
            throw new RRException(ConfigException.PERSONAL_DATA_NOT_EXIST);
        }

        BeanUtil.copyPropertiesIgnoreNull(personalData, data);
        this.baseMapper.updateById(data);
    }

    @Override
    public void saveData(PersonalDataEntity personalData) {

        Date date = DateUtils.addDateDays(new Date(), -1);
        Integer count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<PersonalDataEntity>()
                        .eq(PersonalDataEntity::getMobile, personalData.getMobile())
                        .gt(PersonalDataEntity::getCreateTime, date)
        );
        if (count > 0) {
            throw new RRException(ConfigException.MOBILE_REGISTER);
        }

        this.baseMapper.insert(personalData);
    }

}